package com.snbc.util;

import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PathVerify {
	private boolean isExists;
	private boolean isFile;
	/**
	 * /fsnfile/20160325/201603250065
	 */
	private boolean isSubDir;
	/**
	 * /fsnfile/20160325
	 */
	private boolean isParent;
	private Path path;
	
	
	public boolean isExists() {
		return isExists;
	}
	public void setExists(boolean isExists) {
		this.isExists = isExists;
	}
	public boolean isFile() {
		return isFile;
	}
	public void setFile(boolean isFile) {
		this.isFile = isFile;
	}
	public boolean isSubDir() {
		return isSubDir;
	}
	public void setSubDir(boolean isSubDir) {
		this.isSubDir = isSubDir;
	}
	public boolean isParent() {
		return isParent;
	}
	public void setParent(boolean isParent) {
		this.isParent = isParent;
	}
	public Path getPath() {
		return path;
	}
	public void setPath(Path path) {
		this.path = path;
	}
	public static PathVerify verify(FileSystem fs, String path) throws IOException {
		PathVerify bean=new PathVerify();
		Path p=new Path(path);
		bean.setPath(p);
		if(fs.exists(p)){
			bean.setExists(true);
		}else{
			return bean;
		}
		if(fs.isFile(p)){
			bean.setFile(true);
			return bean;
		}
		String name=p.getName();
		if(12==name.length() && matchDay(name.substring(0, 8)) && match("\\d{4}",name.substring(8))){
			bean.setSubDir(true);
		}
		if(8==name.length() && matchDay(name.substring(0, 8))){
			bean.setParent(true);
		}
		return bean;
	}
	public static boolean matchDay(String str){
		SimpleDateFormat formater=new SimpleDateFormat("yyyyMMdd");
		try {
			Date d=formater.parse(str);
			return str.equals(formater.format(d));
		} catch (ParseException e) {
			e.printStackTrace();
			return false;
		}
	}
	public static boolean match(String regix, String str){
		Pattern pattern = Pattern.compile(regix);
		Matcher matcher = pattern.matcher(str);
		return matcher.matches();
	}

}
